<template>
  <Page class="bg-[#f5f5f5] min-h-screen">
    <PageHeader title="课程详情" />
    <view class="rounded-2xl mx-auto my-4 w-[700rpx]" @click="goToTraining">
      <image :src="getFullPath(courseInformation.cover)" mode="widthFix" class="w-full"></image>
    </view>
    <!-- 课程信息卡片 -->
    <view class="shadow-md p-[32rpx] mx-[24rpx] mt-[32rpx] mb-[24rpx]">
      <view class="courseInformation-title text-[32rpx] font-bold mb-[16rpx] text-[#165DFF]">{{ courseInformation.title }}</view>
      <view class="flex mb-[24rpx] gap-x-8 items-end">
        <view class="flex-1 text-[#666] text-[26rpx]">时长: {{ formatDuration(courseInformation.cycle) }}</view>
        <view class="text-[#666] text-[26rpx]">价格: 
          <text class="text-[#ff0000] text-[26rpx] font-bold">¥{{ courseInformation.price }}</text>
        </view>
        <view class="text-[#666] text-[26rpx]">学员: {{ courseInformation.member_number }}人</view>
      </view>
      <view class="courseInformation-content text-[28rpx] leading-[1.6] text-[#333]">{{ courseInformation.introduction }}</view>
      <view class="courseInformation-title text-[32rpx] font-bold mb-[16rpx] text-[#165DFF] my-4">宣传视频</view>
      <view class="w-full max-h-[400rpx] my-2 overflow-hidden">
        <video :src="getFullPath(courseInformation.video_url)" mode="widthFix" class="w-full max-h-[400rpx]"></video>
      </view>
      
    </view>
    <!-- 分区标题 -->
    <view class="px-[32rpx] py-[24rpx] text-[30rpx] font-bold border-b border-[#eee] bg-[#f9f9f9]">购买记录</view>
    <!-- 购买记录列表 -->
    <view class="bg-white mx-[24rpx] rounded-2xl shadow-md mt-0">
      <template v-if="courseBuyInformation.length>0">
        <view
          v-for="item in courseBuyInformation"
          :key="item.member_id"
          class="border-b border-[#eee] last:border-0 p-[32rpx]"
        >
          <view class="flex justify-between mb-[12rpx]">
            <view class="text-[#666] text-[26rpx]">{{ item.create_time }}</view>
            <view
              class="text-[26rpx] px-[16rpx] py-[4rpx] rounded-lg"
              :class="[
                item.status === 'paid' ? 'bg-[#e8f5e9] text-[#2e7d32]' :
                item.status === 'pending' ? 'bg-[#fff8e1] text-[#FF4D4F]' :
                'bg-[#ffebee] text-[#c62828]'
              ]"
            >
              {{ statusText(item.pay_status) }}
            </view>
          </view>
          <view class="flex justify-between text-[28rpx]">
            <view>用户: {{ item.userName }}</view>
            <view class="font-bold text-[#165DFF]">¥{{ courseInformation.price }}</view>
          </view>
        </view>
      </template>
      <view v-else class="text-center py-[80rpx] text-[#999] text-[28rpx]">暂无购买记录</view>
      
    </view>
    <view class="h-[90rpx]"></view>
    
    <!-- 底部固定区域 -->
    <view class="fixed bottom-0 left-0 right-0 bg-white border-t border-[#eee] px-[32rpx] py-[24rpx] z-50">
      <view class="flex justify-between items-center">
        <!-- 左侧价格信息 -->
        <view class="flex items-center">
          <text class="text-[#666] text-[28rpx] mr-[8rpx]">价格:</text>
          <text class="text-[#FF4D4F] text-[32rpx] font-bold">¥{{ courseInformation.price }}</text>
        </view>
        
        <!-- 右侧取消发布按钮 -->
        <nut-button 
          v-if="courseBuyInformation.length == 0 && courseInformation.status !=5 && courseInformation.status != 6"
          type="primary" 
          class="rounded-2xl text-[28rpx] px-[32rpx] bg-[#165DFF]" 
          @click="cancelPublish"
        >
          取消发布
        </nut-button>
        <nut-button 
          v-if="courseBuyInformation.length && courseInformation.status != 5 && courseInformation.status != 6"
          type="primary" 
          class="rounded-2xl text-[28rpx] px-[32rpx] bg-[#165DFF]" 
          @click="calculatePublish"
        >
          课程结算
        </nut-button>
      </view>
    </view>
    
    <!-- 底部占位，避免内容被固定底部遮挡 -->
    <view class="h-[120rpx]"></view>
  </Page>
</template>

<script setup lang="ts">
import Taro from '@tarojs/taro'
import { ref } from 'vue'
import PageHeader from '@/components/PageHeader.vue'
import {getCurrentInstance} from "@tarojs/runtime";
import {post, getFullPath} from "@/utils/request";
import {formatDuration} from "@/utils/comm";

/**
 * 课程购买记录页面
 * @description 课程信息+购买记录列表，严格按设计稿和Cursor规则实现。
 * @performance 只渲染必要内容，mock数据，移动端适配。
 */

const goBack = () => {
  Taro.navigateBack()
}

const goToTraining = () => {
  Taro.navigateTo({
    url: `/pages/course/training?id=${courseInformation.value.id}`
  })
}

const cancelPublish = () => {
  Taro.showModal({
    title: '确认取消发布',
    content: '确定要取消发布吗？',
    success: (res) => {
      if (res.confirm) {
        post('/training/updateMain', { id: courseInformation.value.id, status: 5 }).then(res => {
          if (res.code == 0) {
            Taro.showToast({ title: '取消发布成功', icon: 'success' })
            setTimeout(() => {
              Taro.navigateBack()
            }, 1500)
          }
          else{
            Taro.showToast({ title: res.data || '取消发布失败', icon: 'none' })
          }
        })
      }
    }
  })
}

const calculatePublish = () => {
  Taro.showModal({
    title: '确认课程结算',
    content: '确定要课程结算吗？',
    success: (res) => {
      if (res.confirm) {
        post('/training/updateMain', { id: courseInformation.value.id, status:  6}).then(res => {
          if (res.code == 0) {
            Taro.showToast({ title: '课程结算成功', icon: 'success' })
            setTimeout(() => {
              Taro.navigateBack()
            }, 1500)
          }
          else{
            Taro.showToast({ title: res.data || '课程结算失败', icon: 'none' })
          }
        })
      }
    }
  })
}



const course = ref({
  title: 'HTML5与CSS3基础教程',
  duration: '20小时',
  price: '99.00',
  students: 128,
  content:
    '本课程从零开始讲解HTML5和CSS3的基础知识，包括HTML5新标签、语义化结构、CSS3选择器、盒模型、Flex布局、响应式设计等核心内容。通过大量实例演示，帮助学员快速掌握现代网页开发基础技术。'
})

const purchaseList = ref([
  { id: 1, time: '2023-05-15 14:30', status: 'paid', user: '张**', amount: '99.00' },
  { id: 2, time: '2023-05-10 09:15', status: 'refund', user: '李**', amount: '99.00' },
  { id: 3, time: '2023-05-08 16:45', status: 'paid', user: '王**', amount: '99.00' },
  { id: 4, time: '2023-05-05 11:20', status: 'pending', user: '赵**', amount: '99.00' }
])

function statusText(status: number) {
  if (status === 1) return '已支付'
  if (status === 0) return '未支付'
  return '有退款'
}

//获取课程信息
getCourseInformation()
const courseInformation = ref({})
async function getCourseInformation() {
  const id = getCurrentInstance().router?.params.id as string||""
  console.log("id是",id)
  if(id){
    const courseDetails = await post('/training/getById',{trainingId:id})
    courseInformation.value = await courseDetails.data.columns
    console.log("课程信息是",courseInformation.value)
    const chapterInformation = await post('/training/update',{id:courseInformation.value?.id})
    console.log('chapterInformation的值',chapterInformation)
  }
 else{
   Taro.showToast({title:"id为空值"})
  }
}

//获取购买信息
getYourPurchaseInformation()
const courseBuyInformation = ref({})
async function getYourPurchaseInformation() {
  const id = getCurrentInstance().router?.params.id as string||""
  console.log("id是",id)
  if(id){
    const courseDetails = await post('/training/mySell',{trainingId:id})
    courseBuyInformation.value = await courseDetails.data.map((item:any) => ({
      ...item.columns
    }));
    console.log("购买信息是",courseBuyInformation.value)
  }
  else{
    Taro.showToast({title:"id为空值"})
  }
}


// 工具函数：输入小时数（字符串），输出 HH:mm:ss
function formatHoursToTime(hoursStr) {
  // 1. 字符串转数字（防御性处理）
  const hours = parseFloat(hoursStr);
  if (isNaN(hours) || hours < 0) {
    return '00:00:00';
  }

  // 2. 小时转秒 → 再转时分秒
  const totalSeconds = hours * 3600; // 1 小时 = 3600 秒
  const hoursFormatted = Math.floor(totalSeconds / 3600);
  const minutesFormatted = Math.floor((totalSeconds % 3600) / 60);
  const secondsFormatted = Math.floor(totalSeconds % 60);

  // 3. 补零格式化
  return `${String(hoursFormatted).padStart(2, '0')}:${String(minutesFormatted).padStart(2, '0')}:${String(secondsFormatted).padStart(2, '0')}`;
}

</script>

<style lang="scss">
.taro-video-container{
  position: relative !important;
}
.taro-video-cover{
  max-height: 400rpx;
  position: relative !important;
}
</style>